package com.andnnl.atomic;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by chenss on 2021/7/7.
 */

public class BarWorker2 implements Runnable {

    private static AtomicBoolean exists = new AtomicBoolean(false);


    private String name;

    public BarWorker2(String name) {
        this.name = name;
    }

    @Override
    public void run() {

        SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");

        if (exists.compareAndSet(false, true)) {

            System.out.println(sdf.format(new Date())+" "+name + " enter");
            System.out.println(sdf.format(new Date())+" "+name + " working");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                // do nothing
            }
            System.out.println(sdf.format(new Date())+" "+name + " leave");
            exists.set(false);
        } else {
            System.out.println(sdf.format(new Date())+" "+name + " give up");
        }

    }


    public static void main(String[] args) throws InterruptedException {
        Executors.newFixedThreadPool(1).submit(()->{
            while (true) {
                exists.set(false);
                TimeUnit.SECONDS.sleep(1);
            }
        });
        for (int i = 0; i < 10; i++) {
            new Thread(new BarWorker2("bar"+i)).start();
            TimeUnit.SECONDS.sleep(1);
        }
//        BarWorker2 bar1 = new BarWorker2("bar1");
//        BarWorker2 bar2 = new BarWorker2("bar2");
//        new Thread(bar1).start();
//        new Thread(bar2).start();



    }


}
//————————————————
//        版权声明：本文为CSDN博主「零度anngle」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//        原文链接：https://blog.csdn.net/zmx729618/article/details/52767736/